class Solution
{
public:
    int furthestBuilding(vector<int> &heights, int bricks, int ladders)
    {
        priority_queue<int, vector<int>, greater<int>> q;
        auto leastBricksNeeded = [&](int num) -> int
        {
            if (ladders == 0)
            {
                return num;
            }
            if (q.size() < ladders)
            {
                q.push(num);
                return 0;
            }
            else
            {
                if (num > q.top())
                {
                    int leastLargest = q.top();
                    q.pop();
                    q.push(num);
                    return leastLargest;
                }
                else
                {
                    return num;
                }
            }
            return 0;
        };
        int n = heights.size();
        int i = 0;
        for (i = 0; i < n - 1; ++i)
        {
            int needBricks = heights[i + 1] - heights[i];
            if (needBricks <= 0)
            {
                continue;
            }
            needBricks = leastBricksNeeded(needBricks);
            if (needBricks > bricks)
            {
                break;
            }
            bricks -= needBricks;
        }
        return i;
    }
};